package com.tanger.im.service.group;

import com.tanger.common.result.ActionResult;
import com.tanger.common.utils.BeanUtils;
import com.tanger.im.entity.ImUserGroup;
import com.tanger.im.entity.IMUserGroupDto;
import com.tanger.im.entity.ImUserGroupMembers;
import com.tanger.im.entity.IMUserGroupVO;
import com.tanger.im.mapper.IMUserGroupRepository;
import com.tanger.im.service.members.IMUserGroupMembersService;
import com.tanger.im.service.notice.IMUserGroupNoticeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * @Description TODO
 * @Author Hchenbin
 * @Date 2023-12-25 15:41
 * @Version 1.0
 */
@Slf4j
@Service
public class IMUserGroupServiceImpl implements IMUserGroupService {

    @Autowired
    private IMUserGroupRepository repository;
    @Autowired
    private IMUserGroupMembersService membersService;
    @Autowired
    private IMUserGroupNoticeService noticeService;

    @Override
    public List<ImUserGroup> findAll(Long userId) {
        List<Long> groupIds = membersService.findAllByUserId(userId);
        if (CollectionUtils.isEmpty(groupIds)) {
            return Collections.emptyList();
        }
        return Optional.ofNullable(repository.findAllById(groupIds)).orElseGet(Collections::emptyList);
    }

    @Override
    public IMUserGroupDto findOne(Long id) {
        return repository.findById(id)
                .map(this::toMap)
                .orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActionResult save(IMUserGroupVO vo) {
        ImUserGroup group = BeanUtils.copyProperties(vo,new ImUserGroup());
        group.setCreateTime(System.currentTimeMillis());
        group.setMembers(vo.getMembersArr().size());

        repository.save(group);
        List<ImUserGroupMembers> members = vo.getMembersArr();
        int i = 0;
        for (ImUserGroupMembers member : members) {
            member.setGroupId(group.getId());
            member.setIsProhibition(0);
            member.setIsAdmin(0);
            member.setIsCreator(0);
            if (i == 0) {
                member.setIsCreator(1);
                member.setIsAdmin(1);
            }
        }
        membersService.save(members);
        return ActionResult.buildResultSuccess("OK");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActionResult update(IMUserGroupVO vo) {
        ImUserGroup group = repository.findById(vo.getId())
                .orElseThrow(() -> new RuntimeException("组群不存在！"));

        repository.saveAndFlush(BeanUtils.copyProperties(vo, group));
        return ActionResult.buildResultSuccess("OK");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActionResult cancel(Long id) {
        repository.findById(id)
                .orElseThrow(() -> new RuntimeException("组群不存在！"));

        membersService.deleteByGroupId(id);
        repository.deleteById(id);
        return ActionResult.buildResultSuccess("OK");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActionResult updateMembers(Long id, Integer members) {
        ImUserGroup group = repository.findById(id)
                .orElseThrow(() -> new RuntimeException("组群不存在！"));
        group.setMembers(members);
        repository.saveAndFlush(group);
        return ActionResult.buildResultSuccess("OK");
    }

    protected IMUserGroupDto toMap(ImUserGroup group) {
        IMUserGroupDto dto = BeanUtils.copyProperties(group, new IMUserGroupDto());
        dto.setMemberArr(membersService.findAll(group.getId()));
        dto.setNotice(noticeService.findOne(group.getId()));
        return dto;
    }
}
